//递归循环树结构
export const loopTree = (data, key, parentKey, callback) => {
    let finded = false;
    try {
        data.forEach((item, index, arr) => {
            if (finded) throw new Error("breakForEach");

            if (item.key === key) {
                finded = true;
                return callback(item, index, parentKey, arr);
            }
            if (item.children != null && item.children != undefined) {
                return loopTree(item.children, key, item.key, callback);
            }
        });
    } catch (e) {
        return true;
    }
    //if (!finded) return callback(null);
};

//删除树节点
export const deleteTreeNode = (data, key) => {
    data.forEach((item, index) => {
        if (item.key === key) {
            //splice被VUE处理过：触发视图更新
            data.splice(index, 1);
        }
        if (item.children != null && item.children != undefined) {
            return deleteTreeNode(item.children, key);
        }
    });
    return data;
};

//查询需要展开的树节点
const expandLoop = (data, level, expandNodes) => {
    data.forEach(item => {
        expandNodes.push(item.key);
        if (item.children != null && item.children != undefined && level > 1) {
            level--;
            expandLoop(item.children, level, expandNodes);
        }
    });
};

export const expandToLevel = (data, level) => {
    let expandNodes = [];
    expandLoop(data, level, expandNodes);
    return expandNodes;
};

//给树结构追加slots属性
export const appendSlotToTree = datas => {
    for (let i in datas) {
        datas[i].scopedSlots = { icon: "icon" };
        if (datas[i].children) {
            appendSlotToTree(datas[i].children);
        }
    }
    return datas;
};

// 根据key查找树节点
export const getTreeNodeBykey = (data, key) => {
    let result = null;
    if (!data) {
        return null;
    }
    for (let i in data) {
        if (result !== null) {
            break;
        }
        let item = data[i];
        if (item.key === key) {
            result = item;
            break;
        } else if (item.children && item.children.length > 0) {
            result = getTreeNodeBykey(item.children, key);
        }
    }
    return result;
};

//置灰树节点
export const disabledTreeNode = (data, keys) => {
    console.log(keys);
    data.forEach(item => {
        item.disabled = false;
        if (keys.indexOf(item.key) > -1) {
            item.disabled = true;
        }
        if (item.children && item.children.length > 0) {
            disabledTreeNode(item.children, keys);
        }
    });
    return data;
};
